package com.example.actionsignin.mvp.view;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.actionsignin.R;
import com.example.actionsignin.entity.FaceImageEntity;
import com.example.actionsignin.entity.LoginEntity;
import com.example.actionsignin.http.HttpUtil;
import com.example.actionsignin.utils.FaceUtil;
import com.example.actionsignin.utils.FileUtil;
import com.example.actionsignin.utils.ToastUtil;

import java.io.File;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 人脸识别
 */

public class FaceActivity extends AppCompatActivity implements
        FaceUtil.OnFaceListener,
        View.OnClickListener{

    private static final String TAG = "FaceActivity";
    private ImageView imageView;
    private TextView textView;

    private String mPath;
    private String mFacePath;

    private FaceUtil faceUtil;

    private String mAid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_face);

        mAid = getIntent().getStringExtra("aid");

        init();
    }

    private void init() {
        initPermission();
        findById();
        initData();
    }

    private void initData() {
        faceUtil = new FaceUtil(this);
        faceUtil.setListener(this);
    }

    private void initPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
            {
                ActivityCompat.requestPermissions(FaceActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
            }else {
                initCameraPermission();
            }
        }else {
            initCameraPermission();
        }
    }

    private void initCameraPermission()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
            {
                ActivityCompat.requestPermissions(FaceActivity.this,new String[]{Manifest.permission.CAMERA},2);
            }else {
                openCamera();
            }
        }else {
            openCamera();
        }
    }

    private void openCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra("camerasensortype",2);
        intent.putExtra("autofocus",true);
        intent.putExtra("fullScreen",false);
        intent.putExtra("showActionIcons",false);
        mPath = FileUtil.getFileName();
        intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(new File(mPath)));
        startActivityForResult(intent,1);
    }

    private void findById() {
        findViewById(R.id.button_activity_face).setOnClickListener(this);
        findViewById(R.id.left_activity_face).setOnClickListener(this);
        findViewById(R.id.up_activity_face).setOnClickListener(this);

        imageView = (ImageView) findViewById(R.id.image_activity_face);
        textView = (TextView) findViewById(R.id.activity_face_text);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.button_activity_face:
                getFaceImage();
                break;
            case R.id.left_activity_face:
                finish();
                break;
            case R.id.up_activity_face:
                initPermission();
                break;
        }
    }

    private void getFaceImage()
    {
        HttpUtil.onSend().getFaceImage()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<FaceImageEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(FaceImageEntity s) {
                        Log.d(TAG, "onNext: " + s.getFace());
//                        mFacePath = FileUtil.WritePhoto(s.getFace());
                        mFacePath = s.getFace();
                        upFile();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d(TAG, "onError: " + e);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void upFile() {

        Log.d(TAG, "upFile: " + mPath);
        Log.d(TAG, "upFile: " + mFacePath);
//        File file1 = new File(mFacePath);
        File file2 = new File(mPath);

        RequestBody body2 = RequestBody.create(MediaType.parse("image/jpg"),file2);

        faceUtil.sendFaceRequest(mFacePath,body2);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode)
        {
            case 1:
                mPath = FileUtil.WritePhoto(mPath);
                Log.d(TAG, "onActivityResult: " + mPath);
                Glide.with(this).load(mPath).into(imageView);
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode)
        {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                {
                    initCameraPermission();
                }else {
                    ToastUtil.INSTANCE(this,"无权限，请打开摄像头！");
                }
                break;
            case 2:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                {
                    openCamera();
                }else {
                    ToastUtil.INSTANCE(this,"无权限，请打开摄像头！");
                }
                break;
        }
    }

    @Override
    public void onFaceOk() {
        textView.setText("识别成功");
        sendSign();
    }

    @Override
    public void onFaceCancel() {
        textView.setText("识别失败");
    }

    private void sendSign() {
        HttpUtil.onSend().onSignAction(mAid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LoginEntity>() {
                    @Override
                    public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@io.reactivex.annotations.NonNull LoginEntity loginEntity) {
                        if (loginEntity.getResult().equals("1"))
                        {
                            ToastUtil.INSTANCE(FaceActivity.this,"签到成功");
                        }else {
                            ToastUtil.INSTANCE(FaceActivity.this,"已签到");
                        }
                        finish();
                    }

                    @Override
                    public void onError(@io.reactivex.annotations.NonNull Throwable e) {
                        Log.d(TAG, "onError: " + e);
                        ToastUtil.INSTANCE(FaceActivity.this,"请打开网络！");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

}
